//
//  MarkedInfo.m
//  FleaFinder
//
//  Created by Hieu Le on 4/10/13.
//  Copyright (c) 2013 Kiwiweb. All rights reserved.
//

#import "MarkedInfo.h"
#import "XmlParserDelegateMarked.h"
#import "CategoryListCollectionViewCell.h"
#import "GoogleMapXmlDataParser.h"
//#import "Map.h"
#import "Category.h"
#import "AddressAnnotation.h"
#import "XmlParserMarkedListInCategory.h"
#import "XmlParserCategoryList.h"
//#import "Common.h"

@interface MarkedInfo ()
{
    Map* theMap;
}
@end

@implementation MarkedInfo

//@synthesize categoryList;
//@synthesize selectedMarketType;

@synthesize lblMarkedName;
@synthesize lblMarkedType;
@synthesize lblDate;
@synthesize lblTime;
@synthesize lblStande;
@synthesize lblRoad;
@synthesize lblCity;
@synthesize tvDesc;
@synthesize viewCategoryCollection;
@synthesize lblArranger;
@synthesize lblEmail;
@synthesize lblHomepage;
@synthesize lblPhone;
@synthesize scroller;
@synthesize imgFacebook;
@synthesize imgTweeter;

@synthesize lblArrangorLabel;
@synthesize lblContactLabel;
@synthesize lblEmailLabel;
@synthesize lblHomepageLabel;
@synthesize lblPhoneLabel;
@synthesize lblFindOsHerLabel;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    
    font = [UIFont fontWithName:@"Georgia" size:13.0];
    font12 = [UIFont fontWithName:@"Georgia" size:12.0];
    fontItalic = [UIFont fontWithName:@"Georgia-BoldItalic" size:12.0];
    commonColor = [UIColor colorWithRed:0.188 green:0.188 blue:0.219 alpha:1.0];
    violetColor = [UIColor colorWithRed:0.407 green:0.278 blue:0.494 alpha:1.0];
    
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    [self.scroller setScrollEnabled:YES];
    
    /*if(!categoryList){
        XmlParserCategoryList *xmlParser = [[XmlParserCategoryList alloc] init];
        [xmlParser parseXML: linkToCategoryList];
        categoryList = [xmlParser getParsedObjects];
    }*/
    
    theMap = nil;

    if(currentMarked){
        [self displayMarketInfo];
    }
}

-(void)viewWillAppear:(BOOL)animated
{
    
    //[imgTweeter setHidden:YES];
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    CGRect rect = [[UIScreen mainScreen] bounds];
    if(rect.size.height < 500){
        //self.view.frame = CGRectMake(0.0, 50.0, rect.size.width, 50.0);
        self.scroller.frame = CGRectMake(0.0, 0.0, rect.size.width, rect.size.height - 120);
        [self.scroller setContentSize:CGSizeMake(rect.size.width, rect.size.height)];
    }
    
    [viewCategoryCollection reloadData];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void) loadXmlData: (NSString*) sourceUrl forMarket:(int)marketId
{
    if(marketId != currentMarked.marketId){
        NSString* url = [NSString stringWithFormat:sourceUrl, marketId];
        
        XmlParserDelegateMarked *xmlParser = [[XmlParserDelegateMarked alloc] init];
        [xmlParser parseXMLMarkedInfo: url];
        currentMarked = xmlParser.currentMarked;
        [self.navigationItem setTitle:currentMarked.markedname];
        
        [self displayMarketInfo];
    }
}

-(void)displayMarketInfo
{
    
    // Marked *currentMarketForMap;
    //currentMarketForMap = currentMarked;
    
    lblMarkedName.font = font;
    [lblMarkedName setTextColor:violetColor];
    
    lblMarkedType.font = font;
    [lblMarkedType setTextColor:commonColor];
    
    lblRoad.font = font;
    [lblRoad setTextColor:commonColor];
    
    lblCity.font = font;
    [lblCity setTextColor:commonColor];
    
    lblDate.font = font12;
    [lblDate setTextColor:commonColor];
    
    lblTime.font = font12;
    [lblTime setTextColor:commonColor];
    
    lblStande.font = font12;
    [lblStande setTextColor:commonColor];
    
    tvDesc.font = font;
    [tvDesc setTextColor:commonColor];
    tvDesc.textAlignment = UITextAlignmentLeft;
    [tvDesc setContentInset:UIEdgeInsetsMake(0, -7, 0, 0)];
    //[tv setNumberOfLines:0];
    //[lblDesc sizeToFit];
    
    lblArranger.titleLabel.font = fontItalic;
    [lblArranger.titleLabel setTextColor:violetColor];
    
    lblEmail.titleLabel.font = fontItalic;
    [lblEmail.titleLabel setTextColor:violetColor];
    
    lblHomepage.titleLabel.font = fontItalic;
    [lblHomepage.titleLabel setTextColor:violetColor];
    
    lblPhone.titleLabel.font = fontItalic;
    [lblPhone.titleLabel setTextColor:violetColor];
    
    lblMarkedName.text = currentMarked.markedname;
    lblMarkedType.text = currentMarked.type;
    lblRoad.text = currentMarked.road;
    lblCity.text = [NSString stringWithFormat:@"%@ %@",currentMarked.zip == nil ? @"" : currentMarked.zip,  currentMarked.city == nil ? @"" : currentMarked.city];
    
    //currentMarked.datefrom = @"25.04.13";
    //currentMarked.dateto = @"26.04.13";
    
    /*NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"dd.MM.yy"];
    NSDate *dateFrom = [dateFormatter dateFromString:currentMarked.datefrom];
    NSDate *dateTo = [dateFormatter dateFromString:currentMarked.dateto];
    NSDate *today =[NSDate dateWithTimeIntervalSinceNow:0];
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *cdatefrom = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:dateFrom];
    NSDateComponents *cdateto = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:dateTo];
    NSDateComponents *cdatetoday = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:today];
    
    NSString *dfrom = currentMarked.datefrom;
    NSString *dto = currentMarked.dateto;
    
    if(cdatefrom.year == cdatetoday.year && cdatefrom.month == cdatetoday.month)
    {
        if(cdatefrom.day == cdatetoday.day)
        {
            dfrom = @"I dag";
        }
        else if(cdatefrom.day - cdatetoday.day == 1){
            dfrom = @"I morgen";
        }
    }
    
    if(cdateto.year == cdatetoday.year && cdateto.month == cdatetoday.month)
    {
        if(cdateto.day == cdatetoday.day)
        {
            dto = @"I dag";
        }
        else if(cdateto.day - cdatetoday.day == 1){
            dto = @"I morgen";
        }
    }*/
    [appDelegate formatDateOfMarket:currentMarked];
    
    lblDate.text = [NSString stringWithFormat:@"d.%@ - %@", (currentMarked.datefrom == nil ? @"" : currentMarked.datefrom), (currentMarked.dateto == nil ? @"" : currentMarked.dateto)];
    lblTime.text = [NSString stringWithFormat:@"Tid: %@ - %@", currentMarked.startat == nil ? @"" : currentMarked.startat, currentMarked.endat == nil ? @"" : currentMarked.endat];
    lblStande.text = [NSString stringWithFormat:@"Stande: %@", currentMarked.stande];
    
    tvDesc.text = currentMarked.desc == nil ? @"" : currentMarked.desc;
    
    
    //show contact info
    
    BOOL isNotBusinessMarket = ![currentMarked.feetype rangeOfString:@"+"].location == NSNotFound;
    
    [lblArrangorLabel setHidden:isNotBusinessMarket];
    [lblContactLabel setHidden:isNotBusinessMarket];
    [lblEmailLabel setHidden:isNotBusinessMarket];
    [lblHomepageLabel setHidden:isNotBusinessMarket];
    [lblPhoneLabel setHidden:isNotBusinessMarket];
    [lblFindOsHerLabel setHidden:isNotBusinessMarket];
    
    [lblArranger setHidden:isNotBusinessMarket];
    [lblEmail setHidden:isNotBusinessMarket];
    [lblHomepage setHidden:isNotBusinessMarket];
    [lblPhone setHidden:isNotBusinessMarket];
    
    [imgFacebook setHidden:isNotBusinessMarket];
    [imgTweeter setHidden:isNotBusinessMarket];
    
    //currentMarked.contact.facebook = @"http://www.bing.com";
    
    if(!isNotBusinessMarket)
    {
        [lblArranger setTitle:currentMarked.contact.contactname forState:UIControlStateNormal];
        [lblEmail setTitle:currentMarked.contact.email forState:UIControlStateNormal];
        [lblHomepage setTitle:currentMarked.contact.homepage forState:UIControlStateNormal];
        [lblPhone setTitle:currentMarked.contact.phone forState:UIControlStateNormal];
        
        [imgFacebook setImage:[UIImage imageNamed:@"dFacebook"] forState:UIControlStateDisabled];
        //[imgFacebook setEnabled:(!([currentMarked.contact.facebook compare:@""] == NSOrderedSame))];
        if([currentMarked.contact.facebook compare:@""] == NSOrderedSame){
            currentMarked.contact.facebook = appDelegate.common.defaultFacebookLink;
        }
        
        [imgTweeter setImage:[UIImage imageNamed:@"dTweeter"] forState:UIControlStateDisabled];
        [imgTweeter setEnabled:!([currentMarked.contact.tweeter compare:@""] == NSOrderedSame)];
    }
    
    [self.viewCategoryCollection setDataSource:self];
    [self.viewCategoryCollection setDelegate:self];
}

- (void)viewDidUnload {
    [self setLblMarkedName:nil];
    [self setLblMarkedType:nil];
    [self setLblDate:nil];
    [self setLblTime:nil];
    [self setLblStande:nil];
    [self setLblRoad:nil];
    [self setLblCity:nil];
    [self setTvDesc:nil];
    [self setViewCategoryCollection:nil];
    [self setLblArranger:nil];
    [self setLblEmail:nil];
    [self setLblHomepage:nil];
    [self setLblPhone:nil];
    [self setScroller:nil];
    [self setImgFacebook:nil];
    [self setImgTweeter:nil];
    [self setImgFacebook:nil];
    [self setImgTweeter:nil];
    [self setLblArrangorLabel:nil];
    [self setLblContactLabel:nil];
    [self setLblEmailLabel:nil];
    [self setLblHomepageLabel:nil];
    [self setLblPhoneLabel:nil];
    [self setLblFindOsHerLabel:nil];
    [super viewDidUnload];
}

#pragma UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [appDelegate.categoryList count];
}

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"CategoryListCollectionViewCell";
    
    CategoryListCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    
    Category* c = (Category*)[appDelegate.categoryList objectAtIndex:indexPath.row];
    cell.lblCategory.text = c.title;
    cell.imgCheck.image = [UIImage imageNamed:@"unchecked.png"];
    
    int count = [currentMarked.categories count];
    for(int i = 0; i < count; ++i){
        if(c.categoryId == ((Category*)[currentMarked.categories objectAtIndex:i]).categoryId){
            cell.imgCheck.image = [UIImage imageNamed:@"checked.png"];
            break;
        }/*else{
            cell.imgCheck.image = [UIImage imageNamed:@"unchecked.png"];
        }*/
    }
    
    cell.lblCategory.font = font12;
    [cell.lblCategory setTextColor:commonColor];

    // Configure the cell...
    //NSLog(@"market id is : %d", currentMarked.marketId);
    return cell;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

-(IBAction)showFacebook:(id)sender
{
    // NSString *defaultFacebookLink;
    
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString: currentMarked.contact.facebook/*appDelegate.common.defaultFacebookLink*/]];
}

-(IBAction)showTweeter:(id)sender
{
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString: currentMarked.contact.tweeter]];
}

- (IBAction)sendEmail:(id)sender {
    
    NSURL *url = [[NSURL alloc] initWithString:[NSString stringWithFormat:@"mailto:?to=%@&subject=%@&body=%@",
                                                [currentMarked.contact.email stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding],
                                                [@"a" stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding],
                                                [@"a" stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]]];
    
    [[UIApplication sharedApplication] openURL:url];
}

- (IBAction)visitHomepage:(id)sender {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString: currentMarked.contact.homepage]];
}

- (IBAction)callContact:(id)sender {
    NSString *phoneNumber = [NSString stringWithFormat: @"telprompt://%@", currentMarked.contact.phone];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNumber]];
}
@end